const jwt = require('jsonwebtoken') //引入jsonwebtoken
let usercache = {};
class TokenParam{
    username : string;
    //userid:string;
    expires:number;
    isTimeout:boolean;
}
function loginToken(username, expires = 7200):string {
    //const rand = Math.random();
    //const userid = uuid.v1();
    const  current = Math.floor(Date.now() / 1000) + expires 
    const token = jwt.sign({ expires : current,username },secret)
    console.log("*************create token*******",token,current + expires,username)
    usercache[token] = {expires:current,username};
    return token
}

function freeToken(token){
    delete usercache[token];
}

var secret = "_iotbase@zw" 
// 解密，验证
function verifyToken(token): TokenParam | null {

    try {
        
        let htoken = usercache[token]
        const  current = Math.floor(Date.now() / 1000)
        if(htoken){
            let tokenp = new TokenParam()
            console.log("****vvvvtoken username***********",htoken.expires,htoken.username)
            tokenp.isTimeout = (current > htoken.expires);
            tokenp.username = htoken.username;
            return tokenp;
        }
        console.log("check token@@@@@@@@@@@",token)
        const result = jwt.verify(token,secret) || {}
        let tokenp :TokenParam = result
        if(tokenp.username == ""){
            return null;
        }
        if(Object.keys(usercache).length >= 200){
            usercache = {};
        }
        tokenp.isTimeout = (current > tokenp.expires);
        usercache[token] = tokenp.expires;
        return tokenp
    } catch (e) {
        console.log(e)
    }
    return null
}

function continueToken(username:string):string{
    return loginToken(username);
}



export {loginToken,freeToken,verifyToken,continueToken};
